package com.ming.learn.from.carl.binary.tree;

import com.ming.commons.utils.Node;
import com.sun.jmx.remote.internal.ArrayQueue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Of20210305LeetCode429 {
    /*
    给定一个 N 叉树，返回其节点值的层序遍历。(即从左到右，逐层遍历)。
     */
    public static void main(String[] args) {
        Node node = new Node(1, Arrays.asList(new Node(2, Arrays.asList(new Node(5)
                , new Node(6))), new Node(3, Arrays.asList(new Node(7))), new Node(4, Arrays.asList(new Node(8)))));
        System.out.println(levelOrder(node));
    }


    /*
    这道题依旧是模板题，只不过一个节点有多个孩子了
     */
    private static List<List<Integer>> levelOrder(Node root) {
        ArrayQueue<Node> que = new ArrayQueue<>(10);
        ArrayList<List<Integer>> result = new ArrayList<>();
        if (root != null) que.add(root);
        while (!que.isEmpty()) {
            int size = que.size();
            ArrayList<Integer> vec = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                Node node = que.remove(0);
                vec.add(node.val);
                for (int j = 0; j < node.children.size(); j++) { // 将节点孩子加入队列
                    if (node.children.get(j)!=null) que.add(node.children.get(j));
                }
            }
            result.add(vec);
        }
        return result;
    }
}
